<script setup>
import { ref, useAttrs, watch } from 'vue';
import { useRouter } from 'vue-router';
import $utils from 'xcore/utils';
import $data from 'xcore/data';
import { Search, Plus } from '@element-plus/icons-vue';
import setting from "./_setting.vue";

// 使用 useAttrs，但此处未看到对 attrs 的具体使用，若无用可移除
const attrs = useAttrs();
const router = useRouter();

// 监听页面标题变化（假设 $utils.watch.pageTitle 是一个自定义的监听函数）
$utils.watch.pageTitle("label");
// 激活的菜单项
const actived = ref(null); // 使用 null 表示未激活状态，比 {} 更清晰

// 菜单数据
const menus = ref([]);
$data.provider.menu.getAll().then(res => {
    menus.value = res; // 直接赋值，更简洁
    console.log(menus.value);

    // 菜单获取完成后，根据当前路由路径查找匹配的菜单项
    const currentPath = router.currentRoute.value.path;
    const matchingMenu = findMenuByPath(menus.value, currentPath);
 
    if (matchingMenu) {
        // 如果找到匹配的菜单项，则在新标签中打开
        openMenu(matchingMenu);
        actived.value=matchingMenu; // 设置激活的菜单项

    }
});


// 递归查找菜单项 by 路径
const findMenuByPath = (menus, path) => {
    for (const menu of menus) {
        if (menu.path === path) {
            return menu;
        }
        if (menu.children && menu.children.length) {
            const childMatch = findMenuByPath(menu.children, path);
            if (childMatch) {
                return childMatch;
            }
        }
    }
    return null;
};




// 点击菜单项的处理函数
const clickMenu = (item) => {
    item.expand = !item.expand;
    if (item.children && item.children.length) return;
    actived.value = item;
    openMenu(item);
};

// 路由和标签页相关
const activeTab = ref('first');
const tabs = ref([]);

// 处理标签页点击
const handleTabClick = () => {
    const tb = tabs.value.find(t => t.id === activeTab.value);
    if (tb) {
        router.push(tb.path);
    }
};

// 打开菜单页面
const openMenu = (menu) => {
    const existingTab = tabs.value.find(tab => tab.id === menu.id);
    if (existingTab) {
        activeTab.value = existingTab.id;
        router.push(existingTab.path);
    } else {
        tabs.value.push({ ...menu });
        activeTab.value = menu.id;
        router.push(menu.path);
    }
};

// 移除标签页
const removeTab = (targetName) => {
    if (tabs.value.length === 1) return;
    const index = tabs.value.findIndex(tab => tab.id === targetName);
    if (index !== -1) {
        tabs.value.splice(index, 1);
    }
    activeTab.value = index > 0 ? tabs.value[index - 1].id : tabs.value[0].id;
};

</script>
<template>
    <div :class="$attrs.class" :style="$attrs.style">
        <!-- 顶部banner -->
        <div class="banner w-100 d-flex align-items-center" v-if="$attrs.bannerGroup.showBanner"
            :style="$attrs.bannerGroup.style">
            <span class="d-inline-block d-flex justify-content-left ms-5 align-items-center w-25"
                v-if="$attrs.bannerGroup.showLogo" :style="$attrs.bannerGroup.showLogoStyle">
                <img class="me-3" :style="{ width: $attrs.bannerGroup.showLogoStyle.logoWidth }"
                    v-if="$attrs.bannerGroup.logoImage" :src="$attrs.bannerGroup.logoImage" />
                {{ $attrs.bannerGroup.system }}
            </span>

            <span class="d-inline-block mx-2 w-100 d-flex justify-content-start" :style="$attrs.bannerGroup.menuStyle"
                v-if="$attrs.bannerGroup.showMenu">
                <!-- <span v-for="item in $attrs.menus" :key="item.id">{{ item.label }}</span> -->
            </span>

            <!-- 顶部 系统设置 -->
            <span class="w-25 me-2 d-flex justify-content-end " v-if="$attrs.bannerGroup.showSetting">
                <setting v-bind="$attrs.bannerGroup"></setting>
            </span>
        </div>
        <!-- 主体 内容区 -->
        <div class="main d-flex justify-content-start w-100"
            :style="{ height: $attrs.bannerGroup.showBanner ? 'calc(100vh - ' + $attrs.bannerGroup.style.height + ')' : '100vh' }">
            <!-- 左侧菜单区 -->
            <div class="menu px-2 pt-2 position-relative overflow-y-auto overflow-x-hidden"
                v-if="$attrs.menuGroup.showMenu" :style="$attrs.menuGroup.style" :class="$attrs.menuGroup.class">
                <div class="my-1 w-100 d-flex justify-content-center align-items-center"
                    v-if="$attrs.menuGroup.showLogo">
                    <span class="d-flex justify-content-center align-items-center rounded-5 bg-white text-center"
                        style="width: 48px; height: 48px;">
                        <i class="iconfont te-i-ai-a fs-4" style="color:#d4237a"></i>
                    </span>
                </div>
                <ul class="px-2">
                    <li v-for="item in menus" :key="item.id">
                        <!-- 一级菜单内容 -->
                        <span v-if="$attrs.menuGroup.showOneLevelMenu" :class="{ active: actived == item }"
                            @click="clickMenu(item)"
                            class="d-flex justify-content-between align-items-center w-100 ps-1">
                            <span>{{ item.label }}</span>
                            <i class="iconfont te-i-jiantou_liebiaoxiangyou "
                                :class="item.expand ? 'te-i-jiantou_liebiaoxiangyo' : 'te-i-jiantou_liebiaozhankai'"
                                v-if="$attrs.menuGroup.showArrow && item.children && item.children.length"></i>

                        </span>
                        <ul v-if="item.children && item.children.length && item.expand">
                            <li v-for="child in item.children" :key="child.id">
                                <span :class="{ active: actived == child }" @click="clickMenu(child)"
                                    class="d-flex justify-content-between align-items-center w-100 ps-2">
                                    <span>{{ child.label }}</span>
                                    <i class="iconfont te-i-jiantou_liebiaoxiangyou"
                                        :class="child.expand ? 'te-i-jiantou_liebiaoxiangyo' : 'te-i-jiantou_liebiaozhankai'"
                                        v-if="$attrs.menuGroup.showArrow && child.children && child.children.length"></i>

                                </span>

                                <ul v-if="child.children && child.children.length && child.expand">
                                    <li v-for="grandchild in child.children" :key="grandchild.id">
                                        <span :class="{ active: actived == grandchild }" @click="clickMenu(grandchild)"
                                            class="d-inline-block w-100 px-4"> {{
                                                grandchild.label }}</span>
                                    </li>
                                </ul>

                            </li>
                        </ul>
                    </li>
                </ul>
                <!-- 左侧菜单 设置栏 -->
                <div v-if="$attrs.menuGroup.showSetting"
                    class="position-absolute bottom-0 start-50 translate-middle-x  d-flex flex-column justify-content-center align-items-center">

                    <setting v-bind="$attrs.menuGroup" class="my-2"></setting>
                </div>
            </div>

            <!-- 右侧内容区 -->
            <div class="content w-100" :class="$attrs.contentGroup.class">
                <span class="d-flex justify-content-center align-items-center" v-if="$attrs.contentGroup.showBar"
                    :class="{ 'mx-1': $attrs.contentGroup.showBar }"
                    >
                    <span v-if="$attrs.contentGroup.showSearch"
                        class=" w-100 d-flex justify-content-center align-items-center w-100">
                        <el-input class="m-2 w-50" v-model="input1" placeholder="请输入搜索内容" :suffix-icon="Search" />
                    </span>
                    <span class="me-2  d-flex justify-content-end align-items-center w-25"
                        :class="$attrs.contentGroup.showSearch ? 'w-25' : 'w-100'"
                        v-if="$attrs.contentGroup.showSetting">
                        <setting v-bind="$attrs.contentGroup"></setting>
                    </span>
                </span>
                <div class="p-2 ps-3 bg-white overflow-y-auto overflow-x-hidden"
                    :class="[{ 'mt-1 mx-1': $attrs.contentGroup.showBar }, $attrs.contentGroup.contentClass]"
                    :style="{ height: $attrs.contentGroup.showBar ? 'calc(100% - 46px)' : 'calc(100%)' }">
                    <el-tabs v-if="$attrs.contentGroup.showTabs" v-model="activeTab" @tab-click="handleTabClick"
                        :closable="tabs.length > 1" @tab-remove="removeTab">
                        <el-tab-pane v-for="tab in tabs" :key="tab.id" :label="tab.label" :name="tab.id" />
                    </el-tabs>
                    <div :style="{'width':'calc(100vw - 60px - '+$attrs.menuGroup.style.width+')'}">
                        <router-view></router-view>
                    </div>
                </div>
            </div>

        </div>
    </div>
</template>

<style scoped>
ul {
    list-style: none;
    font-size: 0.815rem;
    padding-left: 0;
    cursor: pointer;
    margin-bottom: 0;
    margin-top: 0;
}

li span {
    padding: 4px 4px;
    border-radius: 4px;
}

.active,
li>span:hover {
    background-color: v-bind("attrs.menuGroup.style.activeBgColor");
    color: v-bind("attrs.menuGroup.style.activeTextColor");
}
</style>